(function(angular) {
	'use strict';
	angular.module('fs.waf').factory('buService', buService);
	buService.$inject = [ '$q', 'loggerFactory', 'commonService', 'ajaxServiceFactory', 'gridService' ,'modalService', '$filter', '$parse'];
	function buService($q, loggerFactory, commonService, ajaxServiceFactory, gridService, modalService, $filter, $parse) {
		var log = loggerFactory.getLogger("buService"), ajaxService = ajaxServiceFactory.buildAjaxService({
			getBuTypes : {
				url : 'do/cda/dataList/buTypes',
				method : 'get'
			}
		});
		function getBuTypeOptions() {
			var defer = $q.defer();
			ajaxService.getBuTypes().then(function(response) {
				defer.resolve(response.data);
			});
			return defer.promise;
		}
		function initOtherData($scope, ctrl, updateProcessFlag) {
			ctrl.addBuChild = function() {
				var defer = $q.defer();
				var params = {};
				params.buCodes = [];
				if (ctrl.bu.buCode) params.buCodes.push($filter('encode')(ctrl.bu.buCode));
				angular.forEach(ctrl.bu.buChilds, function(child, index) {
					params.buCodes.push(child.childBuCode);
				});
				params.buType = ctrl.bu.buType;
				modalService.openCustomDialogs({
					'dialogsModule' : 'cda.bu',
					'params' : params,
					'btnCallback' : {
						'ok' : function(selectedRows) {
							if (!selectedRows || selectedRows.length == 0) {
								modalService.openErrorDialogs({
									messages : [ 'title.dialogs.info.norecsel' ]
								});
								return false;
							}
							if (!ctrl.bu.buChilds) {
								ctrl.bu.buChilds = [];
							}
							angular.forEach(selectedRows, function(selectedObj, index) {
								selectedRows[index].dataStatus = 'C';
								selectedRows[index].childBuCode = $filter('encode')(selectedRows[index].buCode);
								selectedRows[index].childBuDesc = selectedRows[index].buDesc;
								selectedRows[index].buCode = '';
								ctrl.bu.buChilds.push(selectedRows[index]);
							});
						}
					}
				});
				defer.reject();
				return defer.promise;
			};

			ctrl.addBuCtrl = function() {
				var defer = $q.defer();
				if (!ctrl.bu.buType) {
					//Please select a BU Type first!
					modalService.openErrorDialogs({
						messages : [ 'title.dialogs.info.nobutypeselect' ]
					});
					return false;
				} 
				// params
				var params = {};
				params.buCtrlDatas = [];
				angular.forEach(ctrl.bu.buCtrls, function(buCtrl, index) {
					params.buCtrlDatas.push(buCtrl.buCtrlData);
				});
				// COMPANY/COMPANY_TYPE/COMPANY_CLASS/SEGMENT/INDUSTRY/COUNTRY
				params.currBuCtrlCat = ctrl.bu.currBuCtrlCat;
				params.currBuCtrlProdFlag = ctrl.bu.currBuCtrlProdFlag;
				var buCtrl = {};
				buCtrl.dataStatus = 'C';
				if (!ctrl.bu.buCtrls) {
					ctrl.bu.buCtrls = [];
				}
				ctrl.bu.buCtrls.push(buCtrl);
				defer.reject();
				return defer.promise;
			};
			ctrl.buTypeChanged = function(value) {
				if(ctrl.bu && ctrl.bu.buType) {
					ctrl.bu.buTypeName = ctrl.bu.buType.split(":")[1];
				}
				// ctrl.bu.buType != ctrl.bu.oldBuType for popup multi openConfirmDialogs
				if (((ctrl.bu && ctrl.bu.buChilds && ctrl.bu.buChilds.length > 0) || (ctrl.bu && ctrl.bu.buCtrls && ctrl.bu.buCtrls.length > 0)) 
						&& ctrl.bu.buType != ctrl.bu.oldBuType) {
					//Data in all tabs will lost if you change BU Type, are you sure to change?
					modalService.openConfirmDialogs({
						'messages' : [ 'title.dialogs.info.butypechangewarning' ],
						'btnCallback' : {
							'ok' : function() {
								ctrl.bu.oldBuType = ctrl.bu.buType;
								ctrl.bu.buCtrls = [];
								ctrl.bu.buChilds = [];
								ctrl.bu.changeBuType = "Y";
								// change buType, need reset currBuCtrlCat/currAllowChild/currBuCtrlProdFlag
								if(ctrl.buTypeOptions) {
									for (var i = 0; i < ctrl.buTypeOptions.length; i++) {
										var _buType = ctrl.buTypeOptions[i];
										if (_buType.value == ctrl.bu.buType) {
											ctrl.bu.currBuCtrlCat = _buType.extProperty.buCtrlCat;
											ctrl.bu.currAllowChild = _buType.extProperty.allowChild;
											ctrl.bu.currBuCtrlProdFlag = _buType.extProperty.buCtrlProdFlag;
											changeBuCtrlTabTitle($scope, ctrl);
										}
									}
								}
							},
							'close' : function() {
								ctrl.bu.buType = ctrl.bu.oldBuType;
							}
						}
					});
				} else {
					if(ctrl.bu){
					   ctrl.bu.oldBuType = ctrl.bu.buType;
					}
					// change buType, need reset currBuCtrlCat/currAllowChild/currBuCtrlProdFlag
					if(ctrl.buTypeOptions) {
						for (var i = 0; i < ctrl.buTypeOptions.length; i++) {
							var _buType = ctrl.buTypeOptions[i];
							if (_buType.value == ctrl.bu.buType) {
								ctrl.bu.currBuCtrlCat = _buType.extProperty.buCtrlCat;
								ctrl.bu.currAllowChild = _buType.extProperty.allowChild;
								ctrl.bu.currBuCtrlProdFlag = _buType.extProperty.buCtrlProdFlag;
								changeBuCtrlTabTitle($scope,ctrl);
							}
						}
					}
					
				}
			};
		}
		function changeBuCtrlTabTitle($scope, ctrl, viewFlag) {
			// tab title
			var buCtrlDataOptionId;
			var dynamicSelectField;
			var dialogSize;
			var params = {};
			params.multiSelect = false;
			if (ctrl.bu.currBuCtrlCat == 'COMPANY') {
				buCtrlDataOptionId = 'cda.company';
				dynamicSelectField= "companyCode";
				ctrl.bu.buCtrlTabTitle = 'title.tab.bu.company';
				params.filterCompanyCodesForBu = '<vm.bu.buCtrls';
			} else if (ctrl.bu.currBuCtrlCat == 'COMPANY_TYPE') {
				buCtrlDataOptionId = 'cda.companyType';
				dynamicSelectField= "companyType";
				ctrl.bu.buCtrlTabTitle = 'title.tab.bu.companytype';
				params.filterCompanyTypesForBu = '<vm.bu.buCtrls';
			} else if (ctrl.bu.currBuCtrlCat == 'COMPANY_CLASS') {
				buCtrlDataOptionId = 'cda.companyClass';
				dynamicSelectField= "companyClass";
				ctrl.bu.buCtrlTabTitle = 'title.tab.bu.companyclass';
				params.filterCompanyClassesForBu = '<vm.bu.buCtrls';
				dialogSize = [850, 400];
			} else if (ctrl.bu.currBuCtrlCat == 'SEGMENT') {
				buCtrlDataOptionId = 'cda.segment';
				dynamicSelectField= "segmentCode";
				ctrl.bu.buCtrlTabTitle = 'title.tab.bu.segment';
				params.filterSegmentCodesForBu = '<vm.bu.buCtrls';
			} else if (ctrl.bu.currBuCtrlCat == 'INDUSTRY') {
				buCtrlDataOptionId = 'cda.industry';
				dynamicSelectField= "industryCode";
				ctrl.bu.buCtrlTabTitle = 'title.tab.bu.industry';
				params.filterIndustryCodesForBu = '<vm.bu.buCtrls';
			} else if (ctrl.bu.currBuCtrlCat == 'COUNTRY') {
				buCtrlDataOptionId = 'cda.country';
				dynamicSelectField= "countryCode";
				ctrl.bu.buCtrlTabTitle = 'title.tab.bu.country';
				params.filterCountryCodesForBu = '<vm.bu.buCtrls';
			}
			
			$scope.$on("BUCTRLDATA_OK", function(event, param) {
				var dynamicSelectField = '', currentEntity, returnEntities;
				if (ctrl.bu.currBuCtrlCat == 'COMPANY') {
					dynamicSelectField= "companyCode";
					currentEntity = param.currentEntity;
					returnEntities = param.returnEntities;
					currentEntity['buCtrlData'] = $filter('encode')(returnEntities[0][dynamicSelectField]);
				} else if (ctrl.bu.currBuCtrlCat == 'COMPANY_TYPE') {
					dynamicSelectField= "companyType";
					currentEntity = param.currentEntity;
					returnEntities = param.returnEntities;
					currentEntity['buCtrlData'] = $filter('encode')(returnEntities[0][dynamicSelectField]);
				} else if (ctrl.bu.currBuCtrlCat == 'COMPANY_CLASS') {
					dynamicSelectField= "companyClass";
					currentEntity = param.currentEntity;
					returnEntities = param.returnEntities;
					currentEntity['buCtrlData'] = $filter('encode')(returnEntities[0][dynamicSelectField]);
				} else if (ctrl.bu.currBuCtrlCat == 'SEGMENT') {
					dynamicSelectField= "segmentCode";
					currentEntity = param.currentEntity;
					returnEntities = param.returnEntities;
					currentEntity['buCtrlData'] = $filter('encode')(returnEntities[0][dynamicSelectField]);
				} else if (ctrl.bu.currBuCtrlCat == 'INDUSTRY') {
					dynamicSelectField= "industryCode";
					currentEntity = param.currentEntity;
					returnEntities = param.returnEntities;
					currentEntity['buCtrlData'] = $filter('encode')(returnEntities[0][dynamicSelectField]);
				} else if (ctrl.bu.currBuCtrlCat == 'COUNTRY') {
					dynamicSelectField= "countryCode";
					currentEntity = param.currentEntity;
					returnEntities = param.returnEntities;
					currentEntity['buCtrlData'] = $filter('encode')(returnEntities[0][dynamicSelectField]);
				}
				if('C' != currentEntity.dataStatus) currentEntity.dataStatus = 'U';
				event.preventDefault();
				event.stopPropagation();
			});
			$scope.$on("PRODTYPESHOW_OK", function(event, param) {
				var currentEntity = param.currentEntity;
				var returnEntities = param.returnEntities;
				var prodTypeShow = currentEntity.prodTypeShow || '';
				if (returnEntities && returnEntities.length > 0) {
					currentEntity.buCtrlProds = [];
					for (var i = 0; i < returnEntities.length; i++) {
						returnEntities[i].prodType = $filter('encode')(returnEntities[i].prodType);
						var returnProdType = returnEntities[i].prodType;
						if((prodTypeShow+",").indexOf(returnProdType+",")==-1) {
							if(prodTypeShow) {
								prodTypeShow += "," + returnProdType;
							} else {
								prodTypeShow += returnProdType;
							}
							currentEntity.buCtrlProds.push(returnEntities[i]);
						}
					}
				}
				if (prodTypeShow && prodTypeShow.length > 0 && prodTypeShow.lastIndexOf(",") == prodTypeShow.length - 1) {
					prodTypeShow = prodTypeShow.substr(0, prodTypeShow.length - 1);
				}
				currentEntity.prodTypeShow = prodTypeShow;
				if('C' != currentEntity.dataStatus) currentEntity.dataStatus = 'U';
				event.preventDefault();
				event.stopPropagation();
			});
			var ii8nLabel = "label.bu.buctrldata."
				+ angular.lowercase(ctrl.bu.buType.substring(
						ctrl.bu.buType.indexOf(":") + 1,
						ctrl.bu.buType.length));
			var columnDefs = [
			{
				"name" : "buCtrlData",
				"label" : ii8nLabel,
				"model" : "buCtrlData",
				"type" : "lookup-text",
				"options" : {
					"manualInput" : false,
					"id" : buCtrlDataOptionId,
					"size" : dialogSize,
					"params" : params,
					"boundTo": {
					},
					"okEvent" : true,
					"cancelEvent" : false, 
					"callback": {"changed" : "vm.buCtrlChanged"}
				},
				"placeholder" : "placeholder.bu.buctrldata",
				"tooltip" : "tooltips.bu.buctrldata",
				"help" : "help.bu.buctrldata"
			}, {
				"label" : "label.bu.prodtypeshow",
				"model" : "prodTypeShow",
				"type" : "lookup-text",
				"options" : {
					"manualInput" : false,
					"id" : "cda.prodtype",
					"params" : {
						"filterProdTypesStr" : "<prodTypeShow"
					},
					"okEvent" : true,
					"cancelEvent" : false,
					"callback": {"changed" : "vm.buCtrlChanged"}
				},
				"readonly" : ctrl.bu.currBuCtrlProdFlag != 'Y'
			}, {
				"label" : "label.setup.datastatus",
				"model" : "dataStatus",
				"filter": "status"
			} ];
			ctrl.buCtrlChanged = function (obj, form) {
				//if the input is disabled or readonly the form.$dirty is always false.
				if(form.$dirty && 'C' != obj.dataStatus) obj.dataStatus = 'U';
			}
			var viewColumnDefs = [{
				"label" : "label.bu.buctrldata."
					+ angular.lowercase(ctrl.bu.buType.substring(
							ctrl.bu.buType.indexOf(":") + 1,
							ctrl.bu.buType.length)),
				"model": "buCtrlData"
			},
			{
				"label": "label.bu.prodtypeshow",
				"model": "prodTypeShow"
			},{
				"label": "label.setup.datastatus",
				"model": "dataStatus",
				"filter": "status"
			}];
			angular.forEach(columnDefs, function(columnDef, key) {
				var modelName = columnDef.model;
				if("buCtrlData" == modelName) {
					if(!columnDef.options.boundTo) columnDef.options.boundTo = {};
					columnDef.options.boundTo[dynamicSelectField] = "buCtrlData";
				}
			});
  			if(viewFlag) {
  				ctrl.layoutConfig.formConfigs.ctrl.tableConfigs.table.columnDefs = viewColumnDefs;
  			} else {
  				ctrl.layoutConfig.formConfigs.ctrl.tableConfigs.table.columnDefs = columnDefs;
  			}
  			if(ctrl.validatorConfig.buCtrls && ctrl.validatorConfig.buCtrls.buCtrlData) ctrl.validatorConfig.buCtrls.buCtrlData.ruleInfos[0].errorArgs[0] = ii8nLabel;
  			if(ctrl.validatorConfig) ctrl.layoutConfig.formConfigs.ctrl.tableConfigs.table.validatorConfig = ctrl.validatorConfig.buCtrls;
  			ctrl.ctrlInnerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.ctrl.tableConfigs.table, ctrlRowSelectionChanged);
  			ctrl.ctrlInnerGridOptions.data = 'vm.bu.buCtrls';
  			ctrl.ctrlInnerGridOptions.verifyData = 'vm.buOld.buCtrls';
  			function ctrlRowSelectionChanged(eventRow, selectedRows) {
  				ctrl.selectedBuCtrls = selectedRows;
  			}
		}
		return {
			getBuTypeOptions : getBuTypeOptions,
			changeBuCtrlTabTitle : changeBuCtrlTabTitle,
			initOtherData : initOtherData
		};
	}
})(angular);